package com.example.alibabasentinel.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreaker;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.EventObserverRegistry;
import com.alibaba.csp.sentinel.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * SentinelConfiguration
 *
 * @author zhouxianfeng
 * @date 2021-6-4
 */
@Slf4j
@Configuration
public class SentinelConfiguration implements InitializingBean {


    @Bean
    public BlockExceptionHandler blockExceptionHandler() {
        return new MyDefaultBlockExceptionHandler();
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        EventObserverRegistry.getInstance().addStateChangeObserver("logging",
                (prevState, newState, rule, snapshotValue) -> {
                    if (newState == CircuitBreaker.State.OPEN) {
                        log.info("熔断(name={})打开：{} -> OPEN at {},", rule, prevState.name(),
                                TimeUtil.currentTimeMillis());
                    } else {
                        log.info("熔断(name={})将关闭：{} -> {} at {}", rule, prevState.name(), newState.name(), TimeUtil.currentTimeMillis());
                    }
                });
    }
}
